package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.schedule.dtos.Task;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.pojos.Taskinfo;
import com.heima.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.service.TaskinfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * @author 郭文杰
 * @description 针对表【taskinfo】的数据库操作Service实现
 * @createDate 2023-12-08 19:38:55
 */
@Service
public class TaskinfoServiceImpl extends ServiceImpl<TaskinfoMapper, Taskinfo>
        implements TaskinfoService {

    @Autowired
    TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public Long addTask(Task task) {
        //1 将task任务存入到数据库中
        //保存任务对象
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        this.save(taskinfo);
        //保存任务日志对象
        TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, taskinfoLogs);
        //处理其它字段
        taskinfoLogs.setVersion(1);
        taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
        taskinfoLogsMapper.insert(taskinfoLogs);

        //2 将task任务存入到redis中
        task.setTaskId(taskinfo.getTaskId());
        addTaskToRedis(task);
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        //从数据库中删除任务
        TaskinfoLogs taskinfoLogs = updateDBTask(taskId, ScheduleConstants.CANCELLED);
        //从redis中删除任务
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        String key = task.getTaskType() + "_" + task.getPriority();
        //删除list中任务
        cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        //删除zset中任务
        cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));

        return true;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type     任务类型
     * @param priority 任务优先级
     * @return 任务对象
     */
    @Override
    public Task poll(int type, int priority) {
        log.error("开始从list中拉取task任务");
        //1 操作redis中的任务
        //从list中拉取当前要执行的任务
        String listTaskKey = ScheduleConstants.TOPIC + type + "_" + priority;
        String taskStr = cacheService.lRightPop(listTaskKey);
        if (StringUtils.isEmpty(taskStr)) {
            return null;
        }
        log.error("拉取到list中的task任务 = " + taskStr);
        Task task = JSON.parseObject(taskStr, Task.class);
        //2 操作数据库中的任务
        //删除任务对象,修改任务日志状态
        updateDBTask(task.getTaskId(), ScheduleConstants.EXECUTED);
        log.error("成功拉取到list中的task任务,并修改数据库中task");
        return task;
    }

    /**
     * 定时刷新任务(每1分钟,将zset任务刷新到list中)
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void refreshTaskZsetToList() {
        log.error("每1分钟,将zset任务刷新到list中........start");
        String lock = cacheService.tryLock("ZsetToList", 30 * 1000);
        if (lock != null) {
            //获取zset中所有key
            Set<String> zSetKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            //遍历未来任务的key,获取满足条件的元素(task),存到list中,并把zset中的元素删除
            for (String zSetKey : zSetKeys) {
                //获取list中的所有key
                String listKey = zSetKey.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);
                //获取当前时间执行的task
                Set<String> futureTasks = cacheService.zRangeByScore(zSetKey, 0, System.currentTimeMillis());
                for (String futureTask : futureTasks) {
                    //将task存到list
                    cacheService.lLeftPush(listKey, futureTask);
                    //将task从zset中删除
                    cacheService.zRemove(zSetKey, futureTask);
                }
            }
        }
        log.error("每1分钟,将zset任务刷新到list中........end");
    }

    /**
     * 定时同步任务(每次将未来5分钟之内要执行的任务添加到未来数据队列中)
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void refreshTaskDbToRedis(){
        log.error("每次将未来5分钟之内要执行的任务添加到未来数据队列中.....start");
        String lock = cacheService.tryLock("TaskDbToRedis", 30 * 1000);
        if (lock != null) {
            //1 查询数据中所有任务
            //查询5分钟之内的任务
            LambdaQueryWrapper<Taskinfo> wrapper = new LambdaQueryWrapper<>();
            long futureTime = System.currentTimeMillis() + (5 * 60 * 1000);
            wrapper.le(Taskinfo::getExecuteTime,futureTime);
            List<Taskinfo> taskinfos = this.list(wrapper);
            //2 将任务同步到redis
            //先删除之前redis的任务,再添加
            Set<String> listKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
            Set<String> zsetKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            cacheService.delete(listKeys);
            cacheService.delete(zsetKeys);
            //遍历任务对象,添加到redis中
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            }
        }
        log.error("每次将未来5分钟之内要执行的任务添加到未来数据队列中.....end");
    }

    /**
     * 添加task任务到redis中
     * @param task 任务对象
     */
    private void addTaskToRedis(Task task) {
        //redis的key设计:业务前缀_任务类型_优先级
        String key = task.getTaskType() + "_" + task.getPriority();
        //将当前执行的任务存入到list
        long currentTimeMillis = System.currentTimeMillis();
        if (task.getExecuteTime() <= currentTimeMillis) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= (currentTimeMillis + (5 * 60 * 1000))) {
            //将未来时间之内执行的任务存入到zset
            cacheService.zAdd(
                    ScheduleConstants.FUTURE + key,
                    JSON.toJSONString(task),
                    task.getExecuteTime());
        }
    }


    /**
     * 操作数据库中的任务(删除任务对象 修改任务日志状态)
     *
     * @param taskId 任务id
     * @param status 任务日志状态
     * @return 任务日志对象
     */
    private TaskinfoLogs updateDBTask(long taskId, Integer status) {
        //删除任务对象
        this.removeById(taskId);
        //修改任务日志状态
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);
        return taskinfoLogs;
    }


}